import { Injectable, BadRequestException } from '@nestjs/common';
import { User } from 'src/entities/user/user.entity'; //用户数据
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BUSINESS_ERROR_CODE } from '@/config/error.code';
import { BusinessException } from '@/common/exceptions/business.filter';
import { UserLogin } from 'src/entities/user/user-login.entity'; //用户数据
interface ILogin {
  name: string;
  password: string;
  phone?: string;
  platform_type: string;
}
interface IRegister {
  name: string;
  password: string;
  phone: string;
  platform_type: string;
}
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(UserLogin)
    private readonly UserLoginRepository: Repository<UserLogin>,
  ) {}
  async getUser(body: any) {
    const { name, phone, user_id } = body;
    try {
      // 查询user_login表中是否存在登录token
      const userLogin = await this.UserLoginRepository.findOne({
        where: {
          user_id,
        },
      });
      // token是否失效
      if (!userLogin || !userLogin.token) {
        return {
          code: BUSINESS_ERROR_CODE.COMMON,
          result: 'token已失效',
        };
      }

      const findUser = await this.userRepository.findOne({
        where: { name, phone, user_id },
      });
      if (findUser) {
        return findUser;
      }
      return {
        code: BUSINESS_ERROR_CODE.COMMON,
        result: '用户不存在',
      };
    } catch (error) {
      throw new BusinessException(error);
    }
  }
  async getUserInfo(body) {
    const { name, phone, user_id } = body;
    try {
      //连表查询 user表和user_base表
      const findUser = await this.userRepository
        .createQueryBuilder('user')
        .leftJoinAndSelect('user.user_base', 'user_base')
        .where('user.user_id = :id', { id: user_id })
        .getOne();
      return findUser;
    } catch (error) {
      throw new BusinessException(error);
    }
  }
  async setUserInfo(data) {}
}
